//#define _XOPEN_SOURCE  1
#define _SVID_SOURCE  1
//#define _POSIX_SOURCE  1
//#define _BSD_SOURCE  1
#include <header.h>
#include "/www/server/mysql/include/mysql.h"

void finish_with_error(MYSQL *con) {
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con);
    exit(1);
}

int main() {
    MYSQL *con = mysql_init(NULL);

    if (con == NULL) {
        fprintf(stderr, "mysql_init() failed\n");
        exit(1);
    }

    // 连接到数据库
    if (mysql_real_connect(con, "localhost", "root", "123456", "testdb1", 0, NULL, 0) == NULL) {
        finish_with_error(con);
    }

    // 预处理SQL语句
    const char *stmt_str = "UPDATE t_user SET name=? WHERE id=?";
    MYSQL_STMT *stmt = mysql_stmt_init(con);
    if (!stmt) {
        finish_with_error(con);
    }

    if (mysql_stmt_prepare(stmt, stmt_str, strlen(stmt_str))) {
        finish_with_error(con);
    }

    // 绑定参数
    int id = 2; // 要更新的用户ID
    const char *new_name = "傻逼"; // 新的名字
    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (char *)new_name;
    bind[0].buffer_length = strlen(new_name);
    bind[0].is_null = 0;
    bind[0].length = 0;

    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = (char *)&id;
    bind[1].is_null = 0;
    bind[1].length = 0;

    if (mysql_stmt_bind_param(stmt, bind)) {
        finish_with_error(con);
    }

    // 执行更新操作
    if (mysql_stmt_execute(stmt)) {
        finish_with_error(con);
    }

    printf("Updated %lu rows\n", (unsigned long)mysql_stmt_affected_rows(stmt));

    // 释放资源
    mysql_stmt_close(stmt);
    mysql_close(con);

    return 0;
}